package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.*;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.service.IProjectWorkshopService;

import javax.servlet.http.HttpServletResponse;

/**
 * 厂房Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-08
 */
@Service
public class ProjectWorkshopServiceImpl implements IProjectWorkshopService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectWorkshopMapper projectWorkshopMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private RemoteFileService remoteFileService;
    /**
     * 查询厂房
     *
     * @param id 厂房主键
     * @return 厂房
     */
    @Override
    public ProjectWorkshop selectProjectWorkshopById(Long id)
    {
        return projectWorkshopMapper.selectProjectWorkshopById(id);
    }

    /**
     * 查询厂房列表
     *
     * @param projectWorkshop 厂房
     * @return 厂房
     */
    @Override
    public List<ProjectWorkshop> selectProjectWorkshopList(ProjectWorkshop projectWorkshop)
    {
//        List<Long> districtIds = new ArrayList<Long>();
//        //城市
//        if (projectWorkshop.getCityId()!=null){
//            districtIds.add(projectWorkshop.getCityId());
//            projectWorkshop.setCityIds(districtIds);
//        }else if (projectWorkshop.getCityId()==null && projectWorkshop.getProvinceId() != null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectWorkshop.getProvinceId()));
//            districtIds.add(projectWorkshop.getProvinceId());
//            projectWorkshop.setCityIds(districtIds);
//        }
//        //应急系统
//        if (projectWorkshop.getWshopEmergency() != null && projectWorkshop.getWshopEmergency().equals("H")) {
//            projectWorkshop.setWshopEmergency("有");
//        } else if (projectWorkshop.getWshopEmergency() != null && projectWorkshop.getWshopEmergency().equals("N")) {
//            projectWorkshop.setWshopEmergency("无");
//        }
        //出售价格
        if (projectWorkshop.getWshopSellPrice()!=null){
            String[] split = projectWorkshop.getWshopSellPrice().split("~");
            projectWorkshop.setWshopSellPricelow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectWorkshop.setWshopSellPriceHigh(Long.parseLong(split[1]));
            }
        }
        //租赁价格
        if(projectWorkshop.getWshopLeasePrice()!=null){
            String[] split = projectWorkshop.getWshopLeasePrice().split("~");
            projectWorkshop.setWshopSellPricelow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectWorkshop.setWshopSellPriceHigh(Long.parseLong(split[1]));
            }
        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectWorkshop.setSupplyUserId(SecurityUtils.getUserId());
//        }
        List<ProjectWorkshop> projectWorkshops = projectWorkshopMapper.selectProjectWorkshopListz(projectWorkshop);
//        for (ProjectWorkshop workshop : projectWorkshops) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(workshop.getServicePhone());
//            if (sysUser!=null) {
//                workshop.setContactName(sysUser.getNickName());
//                workshop.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectWorkshops;
    }

    /**
     * 新增厂房
     *
     * @param projectWorkshop 厂房
     * @return 结果
     */
    @Override
    public int insertProjectWorkshop(ProjectWorkshop projectWorkshop)
    {
        projectWorkshop.setSupplyUserId(SecurityUtils.getUserId());
        if (projectWorkshop.getApprovalState()==null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectWorkshop.setApprovalState(1L);
//            } else {
                projectWorkshop.setApprovalState(0L);
//            }
        }
        projectWorkshop.setCreateTime(DateUtils.getNowDate());
        projectWorkshop.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectWorkshop, spaceIndustry);
        spaceIndustry.setSupplyUserId(projectWorkshop.getSupplyUserId());
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectWorkshop.getCreateTime());
        spaceIndustry.setSpaceId(projectWorkshop.getSerialNumber());
        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectWorkshopMapper.insertProjectWorkshop(projectWorkshop);
    }

    private static void extracted(ProjectWorkshop projectWorkshop, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(5);
        spaceIndustry.setReleaseType(projectWorkshop.getReleaseType());
        spaceIndustry.setApprovalState(projectWorkshop.getApprovalState());
        spaceIndustry.setProvinceId(projectWorkshop.getProvinceId());//省份
        spaceIndustry.setCityId(projectWorkshop.getCityId());//城市
//        spaceIndustry.setAreaId();//区域
        spaceIndustry.setSupplyType(projectWorkshop.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectWorkshop.getParkId()));
        spaceIndustry.setHeating(projectWorkshop.getWshopHeating());//供暖
        spaceIndustry.setRefrig(projectWorkshop.getWshopRefrig());//制冷
        spaceIndustry.setPower(projectWorkshop.getWshopPower());//电力
        spaceIndustry.setGas(projectWorkshop.getWshopGas());//燃气
        spaceIndustry.setLeasePrice(projectWorkshop.getWshopLeasePrice());//出售价格
        spaceIndustry.setSellPrice(projectWorkshop.getWshopSellPrice());//租赁价格
        spaceIndustry.setCoverResource(projectWorkshop.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectWorkshop.getWshopName());//园区名称
        spaceIndustry.setSpaceAllSize(projectWorkshop.getWshopAllSize());//空间总面积
        spaceIndustry.setTop(projectWorkshop.getTop());//置顶
        spaceIndustry.setRecomState(projectWorkshop.getRecomState());//热门推荐
    }
    /**
     * 修改厂房
     *
     * @param projectWorkshop 厂房
     * @return 结果
     */
    @Override
    public int updateProjectWorkshop(ProjectWorkshop projectWorkshop)
    {
        if (projectWorkshop.getApprovalState()==null){
            projectWorkshop.setApprovalState(0L);
        }
        projectWorkshop.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectWorkshop,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectWorkshop.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectWorkshop.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByWorkshopId(spaceIndustry);
        return projectWorkshopMapper.updateProjectWorkshop(projectWorkshop);
    }

    /**
     * 批量删除厂房
     *
     * @param ids 需要删除的厂房主键
     * @return 结果
     */
    @Override
    public int deleteProjectWorkshopByIds(Long[] ids)
    {
        List<String> pathList = new ArrayList<>();
        for (ProjectWorkshop projectWorkshop : projectWorkshopMapper.selectProjectWorkshopByIds(ids)) {
            spaceIndustryMapper.deleteSpaceRecomById("厂房",projectWorkshop.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectWorkshop.getVrResource(),
                    projectWorkshop.getImgResource(),
                    projectWorkshop.getCoverResource(),
                    projectWorkshop.getVrcover(),
                    projectWorkshop.getQrCode()
            );
        }
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectWorkshopIds(ids);
        return projectWorkshopMapper.deleteProjectWorkshopByIds(ids);
    }

    /**
     * 删除厂房信息
     *
     * @param id 厂房主键
     * @return 结果
     */
    @Override
    public int deleteProjectWorkshopById(Long id)
    {
        ProjectWorkshop projectWorkshop = projectWorkshopMapper.selectProjectWorkshopById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectWorkshop.getVrResource(),
                projectWorkshop.getImgResource(),
                projectWorkshop.getCoverResource(),
                projectWorkshop.getVrcover(),
                projectWorkshop.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("厂房",projectWorkshop.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectWorkshopId(id);
        return projectWorkshopMapper.deleteProjectWorkshopById(id);
    }
    /**
     * 根据编号查询厂房
     *
     * @param spaceId 编号
     * @param show
     * @return 结果
     */
    @Override
    public Map<String, Object> selectProjectWorkshopByNumber(String spaceId, boolean show) {

        ProjectWorkshop projectWorkshop = projectWorkshopMapper.selectProjectWorkshopByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectWorkshopMapper.updatePageViews(spaceId);
            }
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (list != null && list.size() != 0) {
                projectWorkshop.setCollectState(1L);
            } else {
                projectWorkshop.setCollectState(0L);
            }
        }else {
            projectWorkshop.setCollectState(0L);
        }
        if (projectWorkshop.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectWorkshop.getProvinceId());
            projectWorkshop.setCityName(district.getName());
        }
        if (projectWorkshop.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectWorkshop.getCityId());
            projectWorkshop.setCityName(projectWorkshop.getCityName()+district.getName());
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectWorkshop.getServicePhone());
        if (sysUser!=null){
            projectWorkshop.setContactName(sysUser.getNickName());
            projectWorkshop.setContactPhone(sysUser.getPhonenumber());
            projectWorkshop.setQrCode(sysUser.getCodePic());
        }
//        if (projectWorkshop.getAreaId()!=null){
//            District district = districtMapper.selectDistrictById(projectWorkshop.getAreaId());
//            projectWorkshop.setCityName(projectWorkshop.getCityName()+district.getName());
//        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectWorkshop.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("space",projectWorkshop);
        if (projectWorkshop.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectWorkshop.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectWorkshopBySerialNumber(String spaceId) {
        ProjectWorkshop projectWorkshop = projectWorkshopMapper.selectProjectWorkshopByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectWorkshop.getVrResource(),
                projectWorkshop.getImgResource(),
                projectWorkshop.getCoverResource(),
                projectWorkshop.getVrcover(),
                projectWorkshop.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("厂房",projectWorkshop.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectWorkshopId(projectWorkshop.getId());
        return projectWorkshopMapper.deleteProjectWorkshopById(projectWorkshop.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectWorkshop> projectWorkshops, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectWorkshops) || projectWorkshops.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;

        for (ProjectWorkshop projectWorkshop : projectWorkshops) {
            if (projectWorkshops.indexOf(projectWorkshop)==0&&projectWorkshop.getWshopName().equals("厂房名称")){
                continue;
            }
            count++;
            try {

            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、拍卖 " + projectWorkshop.getWshopName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectWorkshop modal = projectWorkshopMapper.selectProjectWorkshopById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("厂房名称：" + modal.getWshopName() + "<w:br/>");
        stringBuffer.append("供给类型：" + modal.getSupplyType() + "<w:br/>");
        stringBuffer.append("租赁价格：" + modal.getWshopLeasePrice() + "<w:br/>");
        stringBuffer.append("出售价格：" + modal.getWshopSellPrice() + "<w:br/>");
        stringBuffer.append("总面积：" + modal.getWshopAllSize() + "<w:br/>");
        stringBuffer.append("空置面积：" + modal.getWshopFreeSize() + "<w:br/>");
        stringBuffer.append("厂房层高：" + modal.getWshopFloorHeight() + "<w:br/>");
        stringBuffer.append("首层承重：" + modal.getWshopFirstLoad() + "<w:br/>");
        stringBuffer.append("标准层承重：" + modal.getWshopLoad() + "<w:br/>");
        stringBuffer.append("地坪材质：" + modal.getWshopFloorMaterial() + "<w:br/>");
        stringBuffer.append("客梯：" + modal.getWshopElevatorPeople() + "<w:br/>");
        stringBuffer.append("客梯负载：" + modal.getWshopElevatorPeopleLoad() + "<w:br/>");
        stringBuffer.append("货梯：" + modal.getWshopElevatorCargo() + "<w:br/>");
        stringBuffer.append("货梯负载：" + modal.getWshopElevatorCargoLoad() + "<w:br/>");
        stringBuffer.append("行吊设备：" + modal.getWshopCrane() + "<w:br/>");
        stringBuffer.append("消防设施：" + modal.getWshopFireControl() + "<w:br/>");
        stringBuffer.append("应急系统：" + modal.getWshopEmergency() + "<w:br/>");
        stringBuffer.append("供暖：" + modal.getWshopHeating() + "<w:br/>");
        stringBuffer.append("制冷：" + modal.getWshopRefrig() + "<w:br/>");
        stringBuffer.append("新风系统：" + modal.getWshopNather() + "<w:br/>");
        stringBuffer.append("电量：" + modal.getWshopPower() + "<w:br/>");
        stringBuffer.append("燃气：" + modal.getWshopGas() + "<w:br/>");
        stringBuffer.append("水：" + modal.getWshopWater() + "<w:br/>");
        stringBuffer.append("园区类别：" + modal.getParkType() + "<w:br/>");
        stringBuffer.append("区域位置：" + modal.getParkAreaAddress() + "<w:br/>");
        stringBuffer.append("需求面积：" + modal.getWshopNeedSize() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
